#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

const int SERVER_PORT_REFLECTION_V1 = 9021;//回射服务器端口v1
const int SERVER_PORT_REFLECTION_V2 = 9022;//回射服务器端口v2
const int GROUP_CHAT_PORT           = 9023;//群聊服务器

void error_func(std::string errorMsg, int errorCode = 0){
    std::cout<<errorMsg<<std::endl;
    printf("errorCode:%d\r\n", errorCode);
    exit(1);
}

int tcp_create_bind_listen(int port){
    int listenfd;
    struct sockaddr_in serv_addr;
    char* ip = "127.0.0.1";
    int portno = port;
    int errorCode;
    //socket
    listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(listenfd < 0){
        error_func("create socket失败\n");
    }

    //bind到端口
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(ip);
    serv_addr.sin_port = htons(portno);

    errorCode = bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if (errorCode < 0){
        error_func("bind socket失败", errorCode);
    }
    
    //listen //参数5表示listen的队列长度，单线程情况下最多只能有5个client连接到server
    listen(listenfd, 5);

    return listenfd;
}



